package pl.edu.pk.cc.client.chef;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.hibernate.Query;
import org.hibernate.Session;

import pl.edu.pk.cc.common.dto.CCCallHistoryDTO;
import pl.edu.pk.cc.common.dto.CCProjectsDTO;
import pl.edu.pk.cc.common.dto.CCWorkerDTO;
import pl.edu.pk.cc.common.util.CCPermissions;
import pl.edu.pk.cc.server.hibernate.CCHibernateUtil;

/**
 * Servlet implementation class CCChefFunctions
 */
public class CCChefFunctions extends HttpServlet {
	private static final long serialVersionUID = 1L;
	static Session s = CCHibernateUtil.getSessionFactory().getCurrentSession();
	HttpSession sess;
	
	FileItemFactory factory = new DiskFileItemFactory();
	ServletFileUpload upload = new ServletFileUpload(factory);
	SimpleDateFormat df = new SimpleDateFormat("YYYY-MM-DD");
	private static List<Object> worker;
	
	static CCCallHistoryDTO c;
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CCChefFunctions() {
        super();
        // TODO Auto-generated constructor stub
    }


	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	@SuppressWarnings("unchecked")
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String type = request.getParameter("type");
		sess = request.getSession();
		switch(type){
		case "active":
			s = CCHibernateUtil.getSessionFactory().getCurrentSession();
			s.beginTransaction();
			Query q = s.createQuery("from CCProjectsDTO");
			List<CCProjectsDTO> list = q.list();
			String[] check = request.getParameterValues("active");
			for(CCProjectsDTO str : list){
				str.setActive(false);
				for(String st : check){
					if(str.getId() == Long.valueOf(st)){
						str.setActive(true);
					}
					else {
						continue;
					}
					
				}
			}
			s.flush();
			s.getTransaction().commit();
			sess.setAttribute("success", 1); // update
			response.sendRedirect("Index?strona=project");
			break;
		case "new_proj":
			String title = request.getParameter("title");
			String type_p = request.getParameter("type_p");
			String item =request.getParameter("item");
			String company = null;
			boolean active = false;
			if(!type_p.equals("sales")){
				company = item;
				item = null;
			}
			if(request.getParameter("active") != null){
				active = true;
			}
			
			CCProjectsDTO proj = new CCProjectsDTO(title, type_p, item, company, active);
			s = CCHibernateUtil.getSessionFactory().getCurrentSession();
			s.beginTransaction();
			long id = (Long)s.save(proj);
			s.flush();
			s.getTransaction().commit();
			if(id > 0)
			sess.setAttribute("success", 1); // dodano
			else {
				sess.setAttribute("success", 2); // blad
			}
			response.sendRedirect("Index?strona=new_project");
			break;
		case "worker":
			Long id_worker = Long.valueOf(request.getParameter("worker_e"));
			s = CCHibernateUtil.getSessionFactory().getCurrentSession();
			s.beginTransaction();
			
			worker = new ArrayList<Object>();
			CCWorkerDTO w1 =(CCWorkerDTO) s.load(CCWorkerDTO.class, id_worker);
			Date start = w1.getEmp().getStartDate();
			Long diff = new Date().getTime() - start.getTime();
			Long months = Math.round(diff/(1000*60*60*24*30.5));
			worker.add(months);
			Long do_konca = w1.getEmp().getLenght()-months;
			worker.add(do_konca);
			Query query = s.createQuery("from CCCallHistoryDTO where worker=:worker").setLong("worker", id_worker);
			worker.add(query.list().size());
			query = s.createQuery("from CCCallHistoryDTO where worker=:worker group by project").setLong("worker", id_worker);
			worker.add(query.list().size());
			query = s.createQuery("from CCCallHistoryDTO where worker=:worker group by clients").setLong("worker", id_worker);
			worker.add(query.list().size());
			Long sum = 0L;
			for(Object o : query.list()){
				c = (CCCallHistoryDTO) o;
				sum += c.getLength();
			}
			worker.add(sum);
			worker.add(w1.getName());
			worker.add(w1.getSurname());
			s.flush();
			s.getTransaction().commit();
			sess.setAttribute("success", 1);
			response.sendRedirect("Index?strona=worker");
			break;
		}
	}
	
	public static List<Object> getStats(){
		List<Object> list = new ArrayList<Object>();
		
		s = CCHibernateUtil.getSessionFactory().getCurrentSession();
		s.beginTransaction();
		
		Query q = s.createQuery("from CCWorkerDTO");
		list.add(q.list().size()); // liczba pracownikow
		q = s.createQuery("from CCClientDTO");
		list.add(q.list().size());
		q = s.createQuery("from CCAgreementDTO");
		list.add(q.list().size());
		q = s.createQuery("from CCSaleDTO");
		list.add(q.list().size());
		q = s.createQuery("from CCProjectsDTO where active=:active").setParameter("active", true);
		list.add(q.list().size());
		q = s.createQuery("from CCScriptsDTO");
		list.add(q.list().size());
		q = s.createQuery("from CCCallHistoryDTO");
		list.add(q.list().size());
		Long sum = 0L;
		for(Object o : q.list()){
			c = (CCCallHistoryDTO) o;
			sum += c.getLength();
		}
		sum = sum/q.list().size();
		list.add(sum);
		q = s.createQuery("from CCProjectsDTO");
		list.add(q.list().size());
		s.flush();
		s.close();
		
		return list;
	}
	@SuppressWarnings("unchecked")
	public static List<CCProjectsDTO> getProjects(){
		List<CCProjectsDTO> list;
		s = CCHibernateUtil.getSessionFactory().getCurrentSession();
		s.beginTransaction();	
		Query q = s.createQuery("from CCProjectsDTO");
		list = q.list();
		s.flush();
		s.close();
		return list;
	}
	
	@SuppressWarnings("unchecked")
	public static List<CCWorkerDTO> getWorker(){
		List <CCWorkerDTO> list;
		s = CCHibernateUtil.getSessionFactory().getCurrentSession();
		s.beginTransaction();
		Query q = s.createQuery("from CCWorkerDTO w where w.login.permissions=:perm order by w.surname").setParameter("perm", CCPermissions.USER);
		list = q.list();
		s.flush();
		s.close();
		
		return list;
	}
	public static List<Object> getWorkerData() {
		return worker;
	}

}
